import { roleGet, userLogin } from "@/api/user";
import router from "@/router";
console.log("状态机的user模块执行了");
//尝试提取本地存储
let userInfo = null;
let uinfo = localStorage.getItem("userInfo-2303");
if (uinfo) {
  userInfo = JSON.parse(uinfo);
}
export default {
  namespaced: true,
  state() {
    return {
      userInfo,
    };
  },
  mutations: {
    initInfoMut(state, uinfo) {
      state.userInfo = uinfo;
      if (uinfo) {
        localStorage.setItem("userInfo-2303", JSON.stringify(uinfo)); //登录后本地存储
      } else {
        localStorage.removeItem("userInfo-2303"); //退出登录，清除本地存储
      }
    },
  },
  actions: {
    userLoginAct(context, account) {
      userLogin(account).then(async (res) => {
        console.log(res);
        let { data } = res; //用户账户信息，里面包含角色roleId
        let role = await roleGet(data.roleId); //使用角色id，获取对应角色权限
        console.log(role);
        data.roleData = role.data; //给用户信息数据包中，追加角色数据
        context.commit("initInfoMut", data); //状态机存储
        router.push("/");
      });
    },
  },
};
